var mysql = require("mysql"); //加载响应的模块

var connection = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'zhixin',
  timezone: '08:00',
  port: '3306'
});

exports.query = function (sql, arr, callback) {
  //建立链接
  connection.getConnection(function (err, connection) {
    if (err) { throw err; return; }
    connection.query(sql, arr, function (error, results, fields) {
      //将链接返回到连接池中，准备由其他人重复使用
      connection.release();
      if (error) throw error;
      //执行回调函数，将数据返回
      callback && callback(results, fields);
    });
  });
};

var doSQL = (sql, parmas = []) => {
  return new Promise((resolve, reject) => {
    // 从创建的连接池中获取到连接
    connection.getConnection((err, connect) => {
      if (err) {
        reject(err)
      } else {
        connect.query(sql, parmas, function (err, data, fileds) {
          // connection.release()方法释放数据库连接
          connect.release()
          resolve({
            err,
            data,
            fileds
          })
        })
      }
    })
  })
}

// 数据请求成功
var handerResult = (data, total, classify) => {
  return JSON.stringify({
    success: 'true',
    errcode: 0,
    code: 20000,
    msg: '数据请求成功',
    data: data,
    total,
    classify
  })
}

var db = {
  doSQL: doSQL,
  handerResult: handerResult,
}

module.exports = db